package com.yc.demo.d1011.qq;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class QQClient {

    public static void main(String[] args) throws IOException {
        // 構建成功之后, 自动连接服务器
        Socket socket = new Socket("127.0.0.1", 8888);
        InetAddress inetAddress = socket.getInetAddress();
        System.out.println("地址: "+inetAddress.getHostAddress());
        // 获取输入输出流
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
        Scanner scanner = new Scanner(System.in);


        new Thread(()->{
                boolean running = true;
                while(running){
                    byte[] bytes = new byte[1024];
                    int count;
                    try {
                        count = in.read(bytes);
                        String msg = new String(bytes,0,count);
                        System.out.println("收到服務器的消息: "+msg);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        ).start();
        new Thread(()->{
            boolean running = true;
            while(running){
                System.out.print("我说: ");
                String msg = scanner.nextLine();
                try {
                    out.write(msg.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        // 主线程应该在此等待, 再关闭 socket
        // socket.close();
    }

}
